package com.rookie.im.learn.io.mq.producer.service.impl;

import com.rookie.im.learn.io.mq.config.RabbitMQConfig;
import com.rookie.im.learn.io.mq.producer.service.RabbitMQService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class RabbitMQServiceImpl implements RabbitMQService {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Override
    public String direct(String msg) {
        try {
            rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_DIRECT_EXCHANGE, RabbitMQConfig.RABBITMQ_DEMO_DIRECT_ROUTING, getMsg(msg, "direct"));
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
    @Override
    public String fanout(String msg) {
        try {
            rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_FANOUT_EXCHANGE_DEMO_NAME, "", getMsg(msg, "fanout"));
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
    @Override
    public String topic(String msg, String routingKey) {
        try {
            rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_TOPIC_EXCHANGE_NAME, routingKey, getMsg(msg, "topic"));
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
    @Override
    public String headers(String msg, Map<String, String> map) {
        try {
            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            messageProperties.setContentType("UTF-8");
            messageProperties.getHeaders().putAll(map);
            Message message = new Message(msg.getBytes(), messageProperties);
            rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_HEADERS_EXCHANGE_DEMO_NAME, null, message);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    private Map<String, String> getMsg(String msg, String mode) {
        Map<String, String> map =  new HashMap<>();
        map.put("msgId", UUID.randomUUID().toString().replace("-", "").substring(0, 32));
        map.put("time", sdf.format(new Date()));
        map.put("msg", msg);
        map.put("mode", mode);
        return map;
    }
}
